package com.itwlj.service.impl;

import com.itwlj.constant.StatusConstant;
import com.itwlj.mapper.OrderMapper;
import com.itwlj.mapper.UserMapper;
import com.itwlj.service.WorkspaceService;
import com.itwlj.vo.BusinessDataVO;
import com.itwlj.vo.OrderOverViewVO;
import com.itwlj.vo.OrderStats;
import com.itwlj.vo.UserStats;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WorkspaceServiceImpl implements WorkspaceService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 统计营业数据
     *
     * @return
     */
    public BusinessDataVO getBusinessData() {
        /**
         * 营业额：当日已完成订单的总金额
         * 订单完成率：有效订单数 / 总订单数
         * 新增用户：当日新增用户的数量
         */
        Map map = new HashMap();
        map.put("status", StatusConstant.ORDER_COMPLETED);

        //营业额
        Double turnover = orderMapper.sumByMap(map);
        turnover = turnover == null ? 0.0 : turnover;

        //全部订单
        map.put("status", null);
        Integer allOrders = orderMapper.countByMap(map);
        //已完成
        map.put("status", StatusConstant.ORDER_COMPLETED);
        Integer completedOrders = orderMapper.countByMap(map);
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (allOrders != 0) {
            orderCompletionRate = (double) (completedOrders / allOrders);
        }

        //新增用户数
        map.put("create_time", LocalDate.now());
        Integer newUsers = userMapper.countByMap(map);

        //用户总数
        Integer allUsers = userMapper.countByMap(null);

        return BusinessDataVO.builder()
                .turnover(turnover)
                .orderCompletionRate(orderCompletionRate)
                .newUsers(newUsers)
                .allUsers(allUsers)
                .build();
    }

    /**
     * 查询订单管理数据
     *
     * @return
     */
    public List<OrderOverViewVO> getOrderOverView(String start, String end) {
        LocalDate startDate = null;
        LocalDate endDate = null;
        if (start == null || end == null) {
            startDate = LocalDate.now();
            endDate = LocalDate.now();
        } else {
            // 解析日期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            startDate = LocalDate.parse(start, formatter);
            endDate = LocalDate.parse(end, formatter);
        }

        List<OrderOverViewVO> orderOverViewVOList = new ArrayList<>();

        // 遍历每一天，逐天查询
        LocalDate currentDate = startDate;

        while (!currentDate.isAfter(endDate)) {
            Map map = new HashMap();
            map.put("create_time", currentDate);

            //未支付
            map.put("status", StatusConstant.ORDER_UNPAID);
            Integer unpaidOrders = orderMapper.countByMap(map);

            //已支付
            map.put("status", StatusConstant.ORDER_PAID);
            Integer paidOrders = orderMapper.countByMap(map);

            //已发货
            map.put("status", StatusConstant.ORDER_SHIPPED);
            Integer shippedOrders = orderMapper.countByMap(map);

            //运输中
            map.put("status", StatusConstant.ORDER_IN_TRANSIT);
            Integer inTransitOrders = orderMapper.countByMap(map);

            //已收货
            map.put("status", StatusConstant.ORDER_RECEIVED);
            Integer receivedOrders = orderMapper.countByMap(map);

            //已完成
            map.put("status", StatusConstant.ORDER_COMPLETED);
            Integer completedOrders = orderMapper.countByMap(map);

            //取消中
            map.put("status", StatusConstant.ORDER_CANCELING);
            Integer cancelingOrders = orderMapper.countByMap(map);

            //已取消
            map.put("status", StatusConstant.ORDER_CLOSE);
            Integer closeOrders = orderMapper.countByMap(map);

            OrderOverViewVO orderOverViewVO = OrderOverViewVO.builder()
                    .date(currentDate)
                    .unpaidOrders(unpaidOrders)
                    .paidOrders(paidOrders)
                    .shippedOrders(shippedOrders)
                    .inTransitOrders(inTransitOrders)
                    .receivedOrders(receivedOrders)
                    .completedOrders(completedOrders)
                    .cancelingOrders(cancelingOrders)
                    .closeOrders(closeOrders)
                    .build();

            orderOverViewVOList.add(orderOverViewVO);
            // 当前日期加一天
            currentDate = currentDate.plusDays(1);
        }

        return orderOverViewVOList;
    }

    /**
     * 查询用户统计数据
     *
     * @param start
     * @param end
     * @return
     */
    public List<UserStats> getUserStats(String start, String end) {
        // 解析日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(start, formatter);
        LocalDate endDate = LocalDate.parse(end, formatter);

        List<UserStats> userStatsList = new ArrayList<>();

        // 遍历每一天，逐天查询用户数量
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            Map map = new HashMap();
            map.put("create_time", currentDate);

            // 查询当前日期的用户数量
            Integer count = userMapper.countByMap(map);
            userStatsList.add(new UserStats(currentDate, count));

            // 当前日期加一天
            currentDate = currentDate.plusDays(1);
        }

        return userStatsList;
    }

    /**
     * 查询订单统计数据
     *
     * @param start
     * @param end
     * @return
     */
    public List<OrderStats> getOrderStats(String start, String end) {
        // 解析日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(start, formatter);
        LocalDate endDate = LocalDate.parse(end, formatter);

        List<OrderStats> orderStatsList = new ArrayList<>();

        // 遍历每一天，逐天查询订单数量
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            Map map = new HashMap();
            map.put("create_time", currentDate);

            // 查询当前日期的订单数量
            Integer count = orderMapper.countByMap(map);
            orderStatsList.add(new OrderStats(currentDate, count));

            // 当前日期加一天
            currentDate = currentDate.plusDays(1);
        }

        return orderStatsList;
    }

    /**
     * 导出用户统计数据
     *
     * @param response
     * @param start
     * @param end
     */
    public void exportUserStats(HttpServletResponse response, String start, String end) {
        // 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/用户数据报表模板.xlsx");
        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + start + "至" + end);

            //用户总数
            Integer allUsers = userMapper.countByMap(null);
            sheet.getRow(3).getCell(2).setCellValue(allUsers);
            //新增用户数
            Integer newUsers = userMapper.countByMap(Map.of("create_time", LocalDate.now()));
            sheet.getRow(3).getCell(5).setCellValue(newUsers);

            List<UserStats> userStatsList = getUserStats(start, end);
            //填充数据
            for (int i = 0; i < userStatsList.size(); i++) {
                sheet.getRow(6 + i).getCell(2).setCellValue(userStatsList.get(i).getDate().toString());
                sheet.getRow(6 + i).getCell(4).setCellValue(userStatsList.get(i).getCount());
            }

            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出订单统计数据
     *
     * @param response
     * @param start
     * @param end
     */
    public void exportOrderStats(HttpServletResponse response, String start, String end) {
        // 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/订单数据报表模板.xlsx");
        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + start + "至" + end);
            List<OrderOverViewVO> orderOverViewVOList = getOrderOverView(start, end);
            //填充数据
            for (int i = 0; i < orderOverViewVOList.size(); i++) {
                LocalDate date = orderOverViewVOList.get(i).getDate();
                sheet.getRow(4 + i).getCell(1).setCellValue(date.toString());
                sheet.getRow(4 + i).getCell(2).setCellValue(orderOverViewVOList.get(i).getUnpaidOrders());
                sheet.getRow(4 + i).getCell(3).setCellValue(orderOverViewVOList.get(i).getPaidOrders());
                sheet.getRow(4 + i).getCell(4).setCellValue(orderOverViewVOList.get(i).getShippedOrders());
                sheet.getRow(4 + i).getCell(5).setCellValue(orderOverViewVOList.get(i).getInTransitOrders());
                sheet.getRow(4 + i).getCell(6).setCellValue(orderOverViewVOList.get(i).getReceivedOrders());
                sheet.getRow(4 + i).getCell(7).setCellValue(orderOverViewVOList.get(i).getCompletedOrders());
                sheet.getRow(4 + i).getCell(8).setCellValue(orderOverViewVOList.get(i).getCloseOrders());
                sheet.getRow(4 + i).getCell(9).setCellValue(orderOverViewVOList.get(i).getCancelingOrders());
                Double turnover = orderMapper.sumByMap(Map.of("create_time", date, "status", StatusConstant.ORDER_COMPLETED));
                turnover = turnover == null ? 0.0 : turnover;
                sheet.getRow(4 + i).getCell(10).setCellValue(turnover);
            }

            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
